package start.socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) {
        int port = 8080;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);

            // 等待客户端连接
            try (Socket socket = serverSocket.accept()) {
                System.out.println("Client connected");

                // 读取客户端发送的数据
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);

                // 接收客户端的消息
                String message = input.readLine();
                System.out.println("Received from client: " + message);

                // 发送响应消息
                output.println("Hello from Server!");

                System.out.println("Response sent to client");
            } catch (Exception e) {
                System.err.println("Client connection error: " + e.getMessage());
            }
        } catch (Exception e) {
            System.err.println("Server error: " + e.getMessage());
        }
    }
}